<template>
  <div>
    <div class="add">
      <el-card class="lh28">
        <div class="addOrderPopout">
          <!-- <div class="titleL">基本信息</div> -->
          <el-form ref="detail" :model="detail" :rules="rules" label-position="left">
            <el-form-item size="mini" label="配方名称" prop="formulaName">
              <el-select
                v-model="detail.formulaName"
                filterable
                remote
                reserve-keyword
                class="w280"
                clearable
                disabled
                placeholder="请输入配方名称"
                :loading="loading"
                :remote-method="remoteMethod"
                @change="changeName"
              >
                <el-option v-for="item in options.drugs" :key="item.id" :label="item.drugName" :value="item.drugName" />
              </el-select>
            </el-form-item>
            <el-form-item size="mini" label="三方编码">
              <el-input v-model="detail.drugThirdCode" disabled clearable class="w280" />
            </el-form-item>
            <el-form-item size="mini" label="药品编码">
              <el-input v-model="detail.drugCode" disabled clearable class="w280" />
            </el-form-item>
            <el-form-item size="mini" label="版本号">
              <el-input v-model="detail.versionNo" disabled clearable class="w280" />
            </el-form-item>
            <div style="width: 100%">
              <div class="tableBox">
                <el-tabs v-model="editableTabsValue" type="card" @edit="handleTabsEdit">
                  <el-tab-pane
                    v-for="(item, index) in editableTabs"
                    :key="index"
                    :label="item.medicamentType||item.title"
                    :name="index+''"
                  >
                    <div class="flex">
                      <el-form-item size="mini" label="剂型">
                        <el-select
                          v-model="item.medicamentTypeId"
                          placeholder="请选择"
                          value-key="id"
                          class="w280"
                          disabled
                          @change="dosageChange"
                        >
                          <el-option
                            v-for="opt in options.dosage"
                            :key="opt.id"
                            :label="opt.dictValue"
                            :value="opt.id"
                            :disabled="opt.disabled"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item size="mini" label="治疗类型">
                        <el-select v-model="item.cureType" placeholder="请选择" disabled value-key="id" class="w280">
                          <el-option label="治疗" :value="'1'" />
                          <el-option label="调理" :value="'2'" />
                        </el-select>
                      </el-form-item>
                      <el-form-item size="mini" label="单位">
                        <el-select
                          v-model="item.unitCode"
                          placeholder="请选择"
                          value-key="id"
                          class="w280"
                          disabled
                          @change="changeUnitCode"
                        >
                          <el-option
                            v-for="item in options.drugUnitName"
                            :key="item.id"
                            :label="item.drugUnitName"
                            :value="item.id+''"
                          />
                        </el-select>

                      </el-form-item>

                    </div>
                    <div class="flex">
                      <!-- <el-form-item size="mini" label="一剂金额">
                        <el-input
                          v-model="item.oneMedicamentPrice"
                          clearable
                          class="w280"
                          :disabled="nameType == '详情'"
                        />
                      </el-form-item> -->
                      <el-form-item class="conversion" size="mini" label="换算关系">
                        1剂 =
                        <el-input
                          v-model="item.oneMedication"
                          clearable
                          class="w80"
                          :disabled="nameType == '详情'"
                          @change="(value) => changeMedicament(value, 'oneMedication')"
                        /> 付 =
                        <el-input
                          v-model="item.oneBag"
                          clearable
                          class="w80"
                          :disabled="nameType == '详情'"
                          @change="(value) => changeMedicament(value, 'oneBag')"
                        />（单位：{{ drugUnitName?drugUnitName:'袋' }}）/次
                        *
                        <el-input
                          v-model="item.oneNumDay"
                          clearable
                          class="w80"
                          :disabled="nameType == '详情'"
                          @change="(value) => changeMedicament(value, 'oneNumDay')"
                        /> 次/日 *
                        <el-input
                          v-model="item.days"
                          clearable
                          class="w80"
                          :disabled="nameType == '详情'"
                          @change="(value) => changeMedicament(value, 'days')"
                        /> 天 =
                        <el-input
                          v-model="item.unitCoefficient"
                          clearable
                          class="w80"
                          disabled
                          @change="(value) => changeMedicament(value, 'unitCoefficient')"
                        />（单位：{{ drugUnitName?drugUnitName:'袋' }})
                      </el-form-item>
                    </div>
                    <!-- <div class=" conversion">
                      <el-form-item size="mini" label="换算关系">
                        1剂 =
                        <el-input
                          v-model="item.unitCoefficient"
                          clearable
                          disabled
                          class="w80"
                          @change="(value) => changeMedicament(value, 'unitCoefficient')"
                        />
                        {{ drugUnitName? drugUnitName : '单位' }}/天 *
                        <el-input
                          v-model="item.days"
                          clearable
                          disabled
                          class="w80"
                          @change="(value) => changeMedicament(value, 'days')"
                        /> 天 =
                        <el-input v-model="item.oneMedicament" disabled clearable class="w80" />
                        {{ drugUnitName? drugUnitName : '单位' }}
                        <span class="ml50" />
                        1.5剂 =
                        <el-input v-model="item.sesquiMedicament" disabled clearable class="w80" />
                        {{ drugUnitName? drugUnitName : '单位' }}
                      </el-form-item>
                    </div> -->
                    <el-table
                      :data="item.formulaMedicamentDetail"
                      size="small"
                      class="mt20"
                      :cell-style="$style.cellStyle"
                      :header-cell-style="$style.rowClass"
                    >
                      <ElTableColumn label="序号" type="index" width="50" />
                      <ElTableColumn label="原料药品名称" prop="drugName" />
                      <ElTableColumn label="每付用料数量" prop="quantity" />
                      <ElTableColumn label="看诊可删减" prop="allowDeletion">
                        <template slot-scope="{ row }">
                          {{ row.allowDeletion?'是':'否' }}
                        </template>
                      </ElTableColumn>
                      <ElTableColumn label="药品类型" prop="drug_type_name" />
                      <ElTableColumn label="数量规则" prop="quantityRuleRemark" />
                      <ElTableColumn label="属性" prop="attribute_remark" />
                      <ElTableColumn label="药品编码" prop="drugCode" />
                      <ElTableColumn label="三方编码" prop="drugThirdCode" />
                      <ElTableColumn label="单位" prop="drugUnitName" />
                      <ElTableColumn label="总付数用料数量" width="160" prop="totalNum">
                        <template slot-scope="{ row }">
                          {{ (row.drugTypeName == '辅料' && (quantity_rule_name == '1剂固定' || quantity_rule_name == '1剂和1.5剂固定'))? row.quantity:(parseInt(row.quantity * (item.oneMedication || 0) * 100) / 100) }}
                        </template>
                      </ElTableColumn>
                      <!-- <ElTableColumn label="操作" width="80">
                        <template slot-scope="{ row }">
                          <el-button type="primary" size="mini" @click="tapDetail(row.id)">删除</el-button>
                        </template>
                      </ElTableColumn> -->
                    </el-table>
                  </el-tab-pane>
                </el-tabs>
                <!-- <el-button class="addBtn" type="warning" icon="el-icon-plus" circle @click="handleTabsEdit(null, 'add')" /> -->
              </div>
            </div>
            <div class="footer">
              <!-- <el-button type="primary" size="small" @click="createDetail('detail')">提 交</el-button> -->
              <el-button size="small" @click="returnUpper">返 回</el-button>
            </div>
          </el-form>
          <!-- 选择药品 -->
          <addGoods
            v-if="addGoodsShow"
            :goods-id="goods_id"
            @goodsList="getGoodsList"
            @closeAdd="openDialog('关闭选择药品')"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>

// import SidebarItem from './SidebarItem';
import addGoods from '@/components/AddGoods';
import { dictsPullList } from '@/api/dictionaries';
import { allDrugsList, unitList } from '@/api/drugs';
import { processingAllList } from '@/api/processCost';
import { businessAllList } from '@/api/formula';
import { formulaAdd, registerUpdate, registerDetail } from '@/api/formula';
class Detail {
  formulaName = '';
  drugThirdCode = '';
  drugCode = '';
  versionNo = '';
}

class Rules {
  formulaName = [{ required: true, message: '请选择配方名称', trigger: 'blur' }];
}
class Options {
  options = [
    { id: '1', name: '选项一' },
    { id: '2', name: '选项二' },
    { id: '3', name: '选项三' },
    { id: '4', name: '选项四' }
  ];
  dosage = [];
  giftType = [];
  yard = [];
  drugs = [];
  processingCode = [];
  drugUnitName = []
}
export default {
  components: {
    addGoods
  },
  data() {
    return {
      detail: new Detail(), // 分页
      options: new Options(), // 选项
      rules: new Rules(), // 表单校验
      goodsList: [], // 列表
      goods_id: [], // 药品id集合
      addGoodsShow: false, // 选择药品
      nameType: '详情',
      editableTabsValue: '',
      editableTabs: [{
        medicamentTypeId: '',
        medicamentType: '药剂1',
        cureType: '', // 治疗类型
        type: '',
        company: '',
        method: '',
        processingCode: '', // 加工费策略编码
        formulaMedicamentDetail: [],
        oneMedicament: '',
        sesquiMedicament: '',
        name: '0'
      }],
      tabIndex: '0',
      loading: false,
      drugUnitName: ''// 单位
    };
  },

  watch: {
    editableTabsValue: {
      handler() {
        this.options.dosage = this.options.dosage.map(ele => {
          ele.disabled = false;
          this.editableTabs.forEach((item, index) => {
            if (this.editableTabsValue != index && ele.id == item.medicamentTypeId) {
              ele.disabled = true;
            }
          });
          return ele;
        });
      }
    }
  },
  mounted() {
    this.nameType = this.$route.query.nameType;
    this.getOptions();
  },
  methods: {
    async getOptions() {
      const { data } = await dictsPullList({
        dicTypes: ['medicamentType']
      });
      this.options.dosage = data.medicamentType;
      const res = await unitList({});
      this.options.drugUnitName = res ? res.data : [];

      const processingCode = await processingAllList();
      this.options.processingCode = processingCode ? processingCode.data : [];
      // const res = await processingAllList();
      // this.options.processingCode = res;
      // console.log(res);
      this.getDetail();
    },
    async getDetail() {
      const { data } = await registerDetail({ id: this.$route.query.id });
      this.detail.drugThirdCode = data.drugThirdCode;
      this.detail.drugCode = data.drugCode;
      this.detail.formulaName = data.formulaName;
      this.editableTabs = data.formulaMedicament.map((ele, index) => {
        ele.name = index;
        return ele;
      });
      this.editableTabsValue = '0';
      console.log(this.editableTabs);
      this.changeUnitCode(data.formulaMedicament[0].unitCode);
      this.remoteMethod(data.formulaName);
      this.options.dosage = this.options.dosage.map(ele => {
        ele.disabled = false;
        this.editableTabs.forEach((item, index) => {
          if (this.editableTabsValue != index && ele.id == item.medicamentTypeId) {
            ele.disabled = true;
          }
        });
        return ele;
      });
    },
    // 搜索药品
    async remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        const drugs = await allDrugsList({ drugs: query });
        this.options.drugs = drugs.data;
        this.loading = false;
      } else {
        this.options.drugs = [];
      }
    },
    // 改变药品
    changeName(e) {
      this.options.drugs.forEach((item) => {
        if (e == item.drugName) {
          this.detail.drugThirdCode = item.drugThirdCode;
          this.detail.drugCode = item.drugCode;
          // this.drugUnitName = item.drugUnitName;
        }
      });
    },
    openDialog(type, id) {
      switch (type) {
        case '选择药品':
          this.goods_id = this.editableTabs[this.editableTabsValue].formulaMedicamentDetail.map((i) => {
            return i.drugCode;
          });
          this.addGoodsShow = true;
          break;
        case '关闭选择药品':
          this.addGoodsShow = false;
          break;
      }
    },
    // 点击移除
    tapDetail(id) {
      let that = this;
      that.editableTabs[this.editableTabsValue].formulaMedicamentDetail.forEach(function(val, index) {
        if (val.id == id) {
          that.editableTabs[that.editableTabsValue].formulaMedicamentDetail.splice(index, 1);
        }
      });
    },
    tabRules() {
      let tabs = this.editableTabs[this.editableTabsValue]; let msg = '';
      if (!tabs.medicamentTypeId) {
        msg = '请选择剂型';
      }
      if (!tabs.cureType) {
        msg = '请选择治疗类型';
      }
      if (!tabs.processingCode) {
        msg = '请选择加工费模板';
      }
      if (!tabs.unitCoefficient) {
        msg = '请输入单位/天';
      }
      if (!tabs.days) {
        msg = '请输入天数';
      }
      if (msg) {
        this.$message({
          message: msg,
          type: 'warning'
        });
      }
      return msg;
    },
    handleTabsEdit(targetName, action) {
      if (action === 'add') {
        let flag = this.tabRules();
        if (flag) return;
        let newTabName = this.editableTabs.length;
        let newTil = parseInt(newTabName) + 1;
        this.editableTabs.push({
          title: `药剂${newTil}`,
          name: newTabName,
          cureType: '1',
          content: '',
          formulaMedicamentDetail: [],
          oneMedicament: '',
          sesquiMedicament: ''
        });
        this.goodsList = [];
        this.editableTabsValue = newTabName;
      }
      if (action === 'remove') {
        let tabs = this.editableTabs;
        let activeName = this.editableTabsValue;
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
              }
            }
          });
        }

        this.editableTabsValue = activeName;
        this.editableTabs = tabs.filter(tab => tab.name !== targetName);
      }
    },
    // 选中药品
    getGoodsList(list) {
      this.editableTabs[this.editableTabsValue].formulaMedicamentDetail = this.editableTabs[this.editableTabsValue].formulaMedicamentDetail.concat(list);
    },
    // 换算关系
    changeMedicament(value, type) {
      let regP = /^[1-9]\d*$/;
      if (!regP.test(value)) {
        this.$message({
          message: '请输入正整数',
          type: 'warning'
        });
        this.editableTabs[this.editableTabsValue][type] = '';
      }
      let unitCoefficient = this.editableTabs[this.editableTabsValue].unitCoefficient;
      let days = this.editableTabs[this.editableTabsValue].days;
      let oneMedicament = '';
      if (unitCoefficient && days) {
        oneMedicament = unitCoefficient * days;
        this.editableTabs[this.editableTabsValue].oneMedicament = oneMedicament;
        this.editableTabs[this.editableTabsValue].sesquiMedicament = oneMedicament * 1.5;
      } else {
        this.editableTabs[this.editableTabsValue].oneMedicament = '';
        this.editableTabs[this.editableTabsValue].sesquiMedicament = '';
      }
    },
    changePrice(value, $index, type) {
      let reg = /^[1-9]\d*$/;
      let regP = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,3})?$/;
      if (type == 'numGive' && !reg.test(value)) {
        // this.goodsList[$index].give_piece = '';
        this.$message({ message: '请输入正整数', type: 'warning' });
      }
      if (type == 'price' && !regP.test(value)) {
        this.$message({
          message: '请输入数字并最多保留三位小数',
          type: 'warning'
        });
        this.editableTabs[this.editableTabsValue].formulaMedicamentDetail[$index].quantity = '';
        // this.goodsList[$index].reduce_money = '';
      }
    },
    // 选择剂型
    dosageChange(e) {
      this.options.dosage.forEach((item) => {
        if (e == item.id) {
          this.editableTabs[this.editableTabsValue].medicamentType = item.dictValue;
        }
      });
    },
    // 选择单位
    changeUnitCode(val) {
      let drugUnitName = '';
      this.options.drugUnitName.forEach(ele => {
        if (val == ele.id) {
          drugUnitName = ele.drugUnitName;
        }
      });
      this.drugUnitName = drugUnitName;
    },
    // 提交
    createDetail(formName) {
      console.log(this.detail);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let flag = false; let flag2 = false;
          this.editableTabs.forEach(ele => {
            // ele.unitCode = this.drugUnitName;
            if (!ele.formulaMedicamentDetail.length) {
              flag = true;
            }
            ele.formulaMedicamentDetail.forEach(ele => {
              if (!ele.quantity) {
                flag2 = true;
              }
            });
            ele.formulaMedicamentDetailDTO = ele.formulaMedicamentDetail;
          });
          if (flag || flag2) {
            this.$message({
              type: 'warning',
              message: flag ? '请选择药品' : flag2 ? '请输入药品用料数量' : ''
            });
          } else {
            this.detail.formulaMedicamentDTO = this.editableTabs;
            let hintText = this.nameType == '新增' ? `新增${this.detail.formulaName}` : `修改${this.detail.formulaName}`;
            this.hint('create', hintText);
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 确认提示
    hint(status, hintText, row) {
      this.$confirm(`${hintText}, 是否确认?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          switch (status) {
            case 'create':
              this.submitBrand();
              break;
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    // 提交接口
    async submitBrand() {
      console.log(this.detail);
      const res = this.nameType == '新增' ? await formulaAdd({
        ...this.detail
      }) : await registerUpdate({
        ...this.detail,
        id: this.$route.query.id
      });
      this.$notification('操作成功', 'success', res.msg);
      this.dialogVisible = false;
      // this.getList();
      this.returnUpper();

      // console.log(res);
    },
    // 取消按钮
    closeDialog() { },
    // 返回
    returnUpper() {
      this.$store.dispatch('tagsView/delView', this.$route);
      this.$router.back();
    }
  }
};
</script>

<style lang="scss" scoped>
.add {
  background: #fff;
  .addOrderPopout {
    height: 80vh;
    // overflow-y: hidden;
  }
  .input {
    width: 100%;
  }
  .el-form-item {
    margin-bottom: 16px;
    width: 30%;
    ::v-deep.el-form-item__label {
      padding-bottom: 0;
      width: 20%;
      text-align: right;
    }
  }
  ::v-deep.el-dialog {
    height: calc(100vh - 80px);
    overflow-y: auto;
  }
  ::v-deep.el-dialog__body {
    padding: 0 20px 100px;
    position: relative;
  }
}

.el-form--label-left {
  display: flex;
  flex-wrap: wrap;
}
.el-form-item {
  display: flex;
  margin-right: 30px;
}
.tableBox {
  // overflow-y: scroll;
  overflow: auto;
  height: 560px;
  position: relative;
  .addBtn {
    position: absolute;
    right: 0;
    top: 0;
  }
}
.footer {
  position: absolute;
  right: 20px;
  top: 20px;
}
.conversion.el-form-item {
  // margin-bottom: 16px;
  width: calc(70% - 60px);

  ::v-deep.el-form-item__label {
    padding-bottom: 0;
    width: 100px;
    text-align: right;
  }
}
</style>
